package com.lxt.ScreencastGallery;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;

import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

/**
 * 实现的可拖拽视频播放器
 */
public class DraggableVideoView extends FrameLayout {

    private PlayerView playerView;
    private int videoWidth = 0;
    private int videoHeight = 0;

    private float lastTouchX = 0f;
    private float lastTouchY = 0f;
    private boolean dragging = false;
    private boolean pendingCenter = false;

    private boolean isDragging = false;
    private float touchSlop = 3f; // 触摸阈值，用于区分点击和拖拽

    private OnClickListener mOnClickListener;

    public DraggableVideoView(Context context) {
        super(context);
        init();
    }

    public DraggableVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DraggableVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 创建 PlayerView 并添加到容器中
        playerView = new PlayerView(getContext());
        addView(playerView);

        // 设置 PlayerView 的属性
        playerView.setUseController(false);
        playerView.setKeepContentOnPlayerReset(true);

        // 获取系统触摸阈值
        touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    /**
     * 设置视频尺寸
     */
    public void setVideoSize(int width, int height) {
        videoWidth = width;
        videoHeight = height;
        pendingCenter = true;
        requestLayout();
    }

    /**
     * 获取内部的 PlayerView
     */
    public PlayerView getPlayerView() {
        return playerView;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (videoWidth <= 0 || videoHeight <= 0 || getChildCount() == 0) {
            return;
        }

        View child = getChildAt(0);
        LayoutParams lp = (LayoutParams) child.getLayoutParams();

        int parentWidth = getMeasuredWidth();
        int parentHeight = getMeasuredHeight();

        // 根据视频宽高比调整尺寸
        if (videoWidth > videoHeight) {
            // 宽视频：以高度为准进行缩放
            float scale = (float) parentHeight / videoHeight;
            lp.width = (int) (videoWidth * scale);
            lp.height = parentHeight;
        } else if (videoWidth < videoHeight) {
            // 窄视频：以宽度为准进行缩放
            float scale = (float) parentWidth / videoWidth;
            lp.width = parentWidth;
            lp.height = (int) (videoHeight * scale);
        } else {
            // 正方形视频
            lp.width = parentWidth;
            lp.height = parentHeight;
        }

        child.setLayoutParams(lp);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (pendingCenter) {
            centerVideo();
            pendingCenter = false;
        }
    }

    /**
     * 居中视频显示
     */
    private void centerVideo() {
        if (getChildCount() == 0 || videoWidth <= 0 || videoHeight <= 0) return;

        View child = getChildAt(0);
        if (videoWidth > videoHeight) {
            int extra = Math.max(0, child.getWidth() - getWidth());
            child.setTranslationX(-extra / 2f);
            child.setTranslationY(0f);
        } else if (videoWidth < videoHeight) {
            int extra = Math.max(0, child.getHeight() - getHeight());
            child.setTranslationY(-extra / 2f);
            child.setTranslationX(0f);
        } else {
            child.setTranslationX(0f);
            child.setTranslationY(0f);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev == null || getChildCount() == 0) return false;
        View child = getChildAt(0);

        if (videoWidth > videoHeight) {
            return child.getWidth() - getWidth() > 5;
        } else if (videoWidth < videoHeight) {
            return child.getHeight() - getHeight() > 5;
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event == null || getChildCount() == 0) return false;

        View child = getChildAt(0);

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                lastTouchX = event.getX();
                lastTouchY = event.getY();
                dragging = true;
                isDragging = false; // 重置拖拽标志
                return true;

            case MotionEvent.ACTION_MOVE:
                if (!dragging) return true;

                float dx = Math.abs(event.getX() - lastTouchX);
                float dy = Math.abs(event.getY() - lastTouchY);

                // 如果移动距离超过阈值，认为是拖拽
                if (dx > touchSlop || dy > touchSlop) {
                    isDragging = true;
                }

                if (isDragging) {
                    if (videoWidth > videoHeight) {
                        int extra = child.getWidth() - getWidth();
                        if (extra > 0) {
                            float deltaX = event.getX() - lastTouchX;
                            float newTx = child.getTranslationX() + deltaX;

                            if (newTx > 0f) newTx = 0f;
                            float minTx = -extra;
                            if (newTx < minTx) newTx = minTx;

                            child.setTranslationX(newTx);
                        }
                    } else if (videoWidth < videoHeight) {
                        int extra = child.getHeight() - getHeight();
                        if (extra > 0) {
                            float deltaY = event.getY() - lastTouchY;
                            float newTy = child.getTranslationY() + deltaY;

                            if (newTy > 0f) newTy = 0f;
                            float minTy = -extra;
                            if (newTy < minTy) newTy = minTy;

                            child.setTranslationY(newTy);
                        }
                    }
                }

                lastTouchX = event.getX();
                lastTouchY = event.getY();
                return true;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                dragging = false;
                if (!isDragging) {
                    // 如果没有拖拽，触发点击事件
                    performClick();
                }
                return true;
        }

        return super.onTouchEvent(event);
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        super.setOnClickListener(l);
        mOnClickListener = l;
    }

    @Override
    public boolean performClick() {
        if (mOnClickListener != null) {
            mOnClickListener.onClick(this);
            return true;
        }
        return super.performClick();
    }

    public void setPlayer(ExoPlayer player) {
        if (playerView != null) {
            playerView.setPlayer(player);
        }
    }

    /**
     * 重置视频位置到居中
     */
    public void resetPosition() {
        centerVideo();
    }
}